﻿/*******************************************************
Author: 罗敏贵
Explain：
Versions: V 1.0 版
E-mail: minguiluo@163.com
Blogs： http://www.cnblogs.com/luomingui
History:
      CreateDate 2020-08-09 19:22:18
    
*******************************************************/
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;

using Agile.Service.Rbac;

namespace Agile.Service.Reward
{
    ///<summary>
    ///工资表
    ///</summary>
    public interface ISalaryService : IRepository<Salary>
    {
        bool IsExists(string UserID, string SalaryColumnID, DateTime SalaryMonth);
        bool GenerateSalary(string yemo, string wageType);
        DataTable GetPayroll(string keyword, string orgId, string yemo, string wageType);
    }
    ///<summary>
    ///工资表
    ///</summary>
    public partial class SalaryService : BaseRepository<Salary>, ISalaryService
    {
        private readonly IUserService _userService;
        private readonly ISalaryColumnService _salaryColumnService;
        public SalaryService(IUserService userService, ISalaryColumnService salaryColumnService)
        {
            _userService = userService;
            _salaryColumnService = salaryColumnService;
        }
        public bool IsExists(string UserID, string SalaryColumnID, DateTime SalaryMonth)
        {
            if (string.IsNullOrWhiteSpace(UserID)) throw new ArgumentNullException(nameof(UserID));
            if (string.IsNullOrWhiteSpace(SalaryColumnID)) throw new ArgumentNullException(nameof(SalaryColumnID));
            if (SalaryMonth == null) throw new ArgumentNullException(nameof(SalaryMonth));

            var table = this.FindAll("UserID='" + UserID + "' AND SalaryColumnID='" + SalaryColumnID + "' AND SalaryMonth='" + SalaryMonth + "'").ToList();
            if (table != null && table.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 生成工资
        /// </summary>
        /// <param name="yemo"></param>
        /// <param name="wage_Type"></param>
        /// <returns></returns>
        public bool GenerateSalary(string yemo, string wageType)
        {
            if (string.IsNullOrWhiteSpace(yemo)) throw new ArgumentNullException(nameof(yemo));
            if (string.IsNullOrWhiteSpace(wageType)) throw new ArgumentNullException(nameof(wageType));

            var yearMonth = Utils.GetObjTranNull<DateTime>(yemo.Substring(0, 4) + "-" + yemo.Substring(4, 2) + "-" + "01");
            var users = _userService.FindAll().ToList();
            var salaryColumns = _salaryColumnService.FindAll(p => p.ParentID == wageType).OrderBy(p => p.OrderBy).ToList();
            for (int i = 0; i < users.Count; i++)
            {
                var user = users[i];
                for (int j = 0; j < salaryColumns.Count; j++)
                {
                    var salaryColumn = salaryColumns[j];

                    Salary salary = new Salary();
                    salary.UserID = user.ID;
                    salary.SalaryColumnID = salaryColumn.ID;
                    salary.SalaryMonth = yearMonth;
                    switch (salaryColumn.SalaryType)
                    {
                        case SalaryType.Formula:
                            //TODO:解析公式
                            salary.Amount = 0;
                            break;
                        case SalaryType.Input:
                            salary.Amount = salaryColumn.OperateExpression.ToDouble();
                            break;
                        case SalaryType.Fixed:
                            salary.Amount = salaryColumn.OperateExpression.ToDouble();
                            break;
                        case SalaryType.Other:
                            salary.Amount = salaryColumn.OperateExpression.ToDouble();
                            break;
                        default:
                            salary.Amount = salaryColumn.OperateExpression.ToDouble();
                            break;
                    }
                    salary.OrderBy = i + j;

                    if (!IsExists(salary.UserID, salary.SalaryColumnID, salary.SalaryMonth))
                    {
                        Add(salary);
                    }

                }
            }
            return true;
        }
        /// <summary>
        /// 获取工资册
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="yemo">202012</param>
        /// <param name="treeword"></param>
        /// <param name="wage_Type"></param>
        /// <returns></returns>
        public DataTable GetPayroll(string keyword, string orgId, string yemo,  string wageType)
        {
            if (string.IsNullOrWhiteSpace(yemo)) throw new ArgumentNullException(nameof(yemo));
            if (string.IsNullOrWhiteSpace(wageType)) throw new ArgumentNullException(nameof(wageType));

            System.Text.StringBuilder strWhere = new System.Text.StringBuilder();
            if (!string.IsNullOrWhiteSpace(orgId))
            {
                strWhere.Append(" and o.ID=''" + orgId + "'' ");
            }
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                strWhere.Append(" and (b.Name like (''%" + keyword + "%'') OR b.Account like (''%" + keyword + "%'') OR o.name like (''%" + keyword + "%'')) ");
            }
            var yearMonth = Utils.GetObjTranNull<DateTime>(yemo.Substring(0, 4) + "-" + yemo.Substring(4, 2) + "-" + "01");
            string sql = @"
Declare @Cols nvarchar(4000), @SalaryMonth datetime, @Sql nvarchar(4000)
Set @SalaryMonth='{0}'
Select @Cols=Isnull(@Cols+',','')+Rtrim(Quotename(Name))
FROM dbo.reward_salarycolumn WHERE ParentID='{1}'

Set @Sql=N'
;With CTE_Salary As
(
   SELECT a.UserID,b.Name AS UserName,b.Account AS UserCode,o.ID AS OrgID,o.name AS OrgName,a.SalaryMonth,c.Name AS SalaryItem,a.Amount FROM dbo.reward_salary a
	INNER JOIN dbo.rbac_user AS b ON b.ID=a.UserID
	INNER JOIN dbo.base_relevance AS r ON r.FirstId=a.UserID
	INNER JOIN dbo.rbac_organize AS o ON o.ID=r.SecondId
	INNER JOIN dbo.reward_salarycolumn AS c ON c.ID=a.SalaryColumnID
	Where SalaryMonth=@SalaryMonth {2}
)
Select * From CTE_Salary Pivot(Max(Amount) For SalaryItem In('+@Cols+')) As b
'
Exec sp_executesql  @Sql,N'@SalaryMonth datetime',@SalaryMonth
";
            sql = string.Format(sql, yearMonth, wageType, strWhere.ToString());
            var talbe = DBA.ExecuteDataTable(sql);
            return talbe;
        }
    }
}